using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Nirvana.Common;
using UnityEditor;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

namespace Nirvana.SkillEditor
{
    public static class SkillActionBuilder
    {
        private static readonly string _skillExportJsonPath = Application.dataPath + "/NirvanaToolkit/SkillEditor/Runtime/SkillJsonData";
        private static readonly string _skillAllFilePath = Application.dataPath + "/NirvanaToolkit/SkillEditor/SkillData";
        private static readonly string _skillAssetFilePath = "Assets/NirvanaToolkit/SkillEditor/SkillData";
        private static readonly string _skillNameFilePath = Application.dataPath + "/NirvanaToolkit/SkillEditor/Runtime";
            
        private static JsonSerializerSettings _jsonSerializerSettings = new()
        {
            TypeNameHandling = TypeNameHandling.All,
            NullValueHandling = NullValueHandling.Ignore,
            DefaultValueHandling = DefaultValueHandling.Ignore,
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            MissingMemberHandling = MissingMemberHandling.Ignore,
            ContractResolver = new ExcludePropertiesContractResolver(new[] {"foldout"})
        };

        public static List<SkillSource> BuildSkillSources()
        {
            var result = new List<SkillSource>();
            if (Directory.Exists(_skillAllFilePath))
            {
                var playables = Directory.GetFiles(_skillAllFilePath, "*.playable", SearchOption.AllDirectories);
                foreach (var playableFilePath in playables)
                {
                    var path = playableFilePath.ToAssetPath();
                    var dic = Path.GetDirectoryName(path.Replace(_skillAssetFilePath + "/", ""));
                    var playableAsset = AssetDatabase.LoadAssetAtPath<PlayableAsset>(path);
                    var skillSource = BuildSkillSource(playableAsset, dic, false);
                    if (skillSource != null)
                    {
                        result.Add(skillSource);
                    }
                }
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            
            return result;
        }
        
        public static SkillSource BuildSkillSource(PlayableAsset playableAsset, string dictionary = "", bool refreshEditor = true)
        {
            SkillSource skillSource = null;
            if (playableAsset != null)
            {
                foreach (var playableBinding in playableAsset.outputs)
                {
                    if (playableBinding.sourceObject is PlayableTrack playableTrack)
                    {
                        foreach (var clip in playableTrack.GetClips())
                        {
                            if (clip.asset is SkillPlayableAsset skillPlayableAsset)
                            {
                                if (skillPlayableAsset.action != null)
                                {
                                    var action = skillPlayableAsset.action;
                                    if (action.actions.Count > 0)
                                    {
                                        action.SetDelayAndDuration(clip.start, clip.duration);
                                        skillSource = new SkillSource();
                                        skillSource.actions.AddRange(action.actions);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(dictionary))
            {
                dictionary += "/";
            }
            var path = $"{_skillExportJsonPath}/{dictionary}{playableAsset.name}.json";
            
            if (skillSource != null)
            {
                FileUtils.Write(path, JsonConvert.SerializeObject(skillSource, Formatting.Indented, _jsonSerializerSettings), true);
                if (refreshEditor)
                {
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                }
            }
            else if (File.Exists(path))
            {
                AssetDatabase.DeleteAsset(path.ToAssetPath());
            }

            return skillSource;
        }

        public static void BuildSkillEnumCSharpScript()
        {
            if (Directory.Exists(_skillAllFilePath))
            {
                var playables = Directory.GetFiles(_skillAllFilePath, "*.playable", SearchOption.AllDirectories);
                if (playables.Length > 0)
                {
                    var builder = new StringBuilder();
                    builder.AppendLineEx("// ------");
                    builder.AppendLineEx("// Automatically generate scripts, do not modify them");
                    builder.AppendLineEx("// ------");
                    builder.AppendLineEx("namespace Nirvana.SkillEditor");
                    builder.AppendLineEx("{");
                    builder.AppendLineEx("\tpublic enum SkillName");
                    builder.AppendLineEx("\t{");
                    foreach (var playableFilePath in playables)
                    {
                        var fileName = Path.GetFileNameWithoutExtension(playableFilePath);
                        builder.AppendLineEx($"\t\t{fileName},");
                    }
                    builder.AppendLineEx("\t}");
                    builder.AppendLineEx("}");
                    FileUtils.Write(_skillNameFilePath + "/SkillName.cs", builder.ToString());
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                }
            }
        }
    }
}
